import datetime
import time

from sqlalchemy import or_, Integer, func
from sqlalchemy.orm import Session

from module_admin.entity.do.cms_car import CmsCar
from module_admin.entity.do.cms_device import CmsDevice
from module_admin.entity.do.cms_order_execute import CmsOrderExecute
from module_admin.entity.vo.cms_device_vo import DeviceModel, DeviceForQuery
from module_admin.entity.vo.cms_home_vo import MyTime
from utils.time_format_util import object_format_datetime, list_format_datetime


class CmsDeviceDao:
    """
    部门管理模块数据库操作层
    """

    @classmethod
    def create_device(cls, db: Session, page_object: DeviceModel):
        object_dict = page_object.dict()
        if "warranty_period_desc" in object_dict:
            del object_dict["warranty_period_desc"]
        cms_device = CmsDevice(**object_dict)
        db.add(cms_device)
        db.flush()
        return cms_device

    @classmethod
    def delete_device_by_id(cls, db: Session, id: int):
        db.query(CmsDevice) \
            .filter(CmsDevice.id == id) \
            .delete()

    @classmethod
    def update_device_by_id(cls, db: Session, device_update_dict: dict):
        db.query(CmsDevice) \
            .filter(CmsDevice.id == device_update_dict.get('id')) \
            .update(device_update_dict)

    @classmethod
    def get_device_by_id(cls, db: Session, id: int):
        first = db.query(CmsDevice).filter(CmsDevice.id == id).first()
        return object_format_datetime(first)

    @classmethod
    def list(cls, db: Session, query_object: DeviceForQuery):
        query = db.query(CmsDevice)
        filters = []
        now = datetime.datetime.now()
        if query_object.device_id and query_object.device_id.strip():
            filters.append(CmsDevice.car_device_no.like(f'%{query_object.device_id}%'))
        if query_object.device_type and query_object.device_type.strip():
            filters.append(CmsDevice.state == query_object.device_type)
        if query_object.warranty_period == '过保':
            filters.append(CmsDevice.warranty_period < now.strftime('%Y-%m-%d %H:%M:%S'))
        if query_object.warranty_period == '在保':
            filters.append(CmsDevice.warranty_period >= now.strftime('%Y-%m-%d %H:%M:%S'))
        if filters:
            query = query.filter(*filters)
        post_list = query.order_by(CmsDevice.create_time.desc()).all()
        return list_format_datetime(post_list)

    @classmethod
    def order_satrt_device_num(cls, db: Session, time: MyTime):
        mileage = db.query(func.count(CmsDevice.id)) \
            .join(CmsCar, CmsCar.device_id == CmsDevice.device_id) \
            .join(CmsOrderExecute, CmsOrderExecute.car_id == CmsCar.car_id) \
            .filter(CmsOrderExecute.create_time >= time.start_time.strftime('%Y-%m-%d %H:%M:%S')) \
            .filter(CmsOrderExecute.create_time < time.end_time.strftime('%Y-%m-%d %H:%M:%S')) \
            .scalar()
        return mileage if mileage is not None else 0
